package com.sheep.jucdemo.part2.part2_9;

import sun.misc.Unsafe;

/**
 * @Date 2022/4/13 20:30
 * @Created by sheep
 */
public class Test2_9_2 {

    // 获取Unsafe的实例
    static final Unsafe unsafe = Unsafe.getUnsafe();

    // 记录变量state在类Test2_9_2中的偏移量
    static final long stateOffset;

    // 变量
    private volatile long state = 0;

    static {
        try {
            // 获取state变量在类中Test2_9_2中的偏移量
            stateOffset = unsafe.objectFieldOffset(Test2_9_2.class.getDeclaredField("state"));
        }catch (Exception e){
            System.out.println(e.getLocalizedMessage());
            throw new Error(e);
        }
    }

    public static void main(String[] args) {

        // 创建实例，并且设置state值为1
        Test2_9_2 test = new Test2_9_2();
        // 如果test对象中内存偏移量stateOffset的state变量的值为0，则更新值为1
        boolean success = unsafe.compareAndSwapInt(test, stateOffset, 0, 1);
        System.out.println(success);
    }
}
